﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using LeafulWeiboSdk.Metadata;
using Newtonsoft.Json;

namespace LeafulWeiboSdk
{
    public class Swap
    {

        public static async Task<string> HttpGetWeiboJsonAsync(string api, params object[] paras)
        {
            if (paras.Count() % 2 != 0) throw new Exception("paras error");
            var query = string.Empty;
            for (var i = 0; i < paras.Count() / 2; i++)
            {
                if (paras[i*2 + 1] == null || string.IsNullOrEmpty(paras[i*2 + 1].ToString()) || paras[i*2 + 1].ToString() == "null") continue;
                query += string.Format("{2}{0}={1}", paras[i*2], paras[i*2 + 1], i > 0 ? "&" : "?");
            }
            using (var client = new HttpClient())
            {
                return await client.GetStringAsync(api + query);
            }
        }

        public static async Task<T> GetMetadataViaHttpGetAsync<T>(string api, params object[] paras)
            where T : BaseMetadata, new()
        {
            try
            {
                var json = await HttpGetWeiboJsonAsync(api, paras);
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                var meta = new T { Exception = ex };
                return meta;
            }
        }

        public static async Task<string> HttpPostWeiboJsonAsync(string api, params object[] paras)
        {
            if (paras.Count() % 2 != 0) throw new Exception("paras error");
            var keyValuePairs = new List<KeyValuePair<string, string>>();
            for (var i = 0; i < paras.Count() / 2; i++)
            {
                if (paras[i * 2 + 1] == null || string.IsNullOrEmpty(paras[i * 2 + 1].ToString()) || paras[i * 2 + 1].ToString() == "null") continue;
                keyValuePairs.Add(new KeyValuePair<string, string>(paras[i * 2].ToString(), paras[i * 2 + 1].ToString()));                
            }
            using (var client = new HttpClient())
            {
                var result = await client.PostAsync(api, new FormUrlEncodedContent(keyValuePairs));
                return await result.Content.ReadAsStringAsync();
            }
        }

        public static async Task<T> GetMetadataViaHttpPostAsync<T>(string api, params object[] paras)
            where T : BaseMetadata, new()
        {

            try
            {
                var json = await HttpPostWeiboJsonAsync(api, paras);
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                var meta = new T { Exception = ex };
                return meta;
            }
        }

        public static async Task<string> PostWeiboJsonComplexAsync(string api, params object[] paras)
        {
            if (paras.Count() % 2 != 0) throw new Exception("paras error");
            var query = string.Empty;
            var content = new MultipartFormDataContent();
            for (var i = 0; i < paras.Count() / 2; i++)
            {
                if (paras[i*2 + 1] == null) continue;
                query += string.Format("{2}{0}={1}", paras[i*2], paras[i*2 + 1], i > 0 ? "&" : "?");
            }
            
            using (var client = new HttpClient())
            {
                
                var result = await client.PostAsync(api, content);
                return await result.Content.ReadAsStringAsync();
            }
            
        }

        public static async Task<T> GetMetadataViaHttpPostComplexAsync<T>(string api, params object[] paras)
            where T : BaseMetadata, new()
        {

            try
            {
                var json = await HttpPostWeiboJsonAsync(api, paras);
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                var meta = new T { Exception = ex };
                return meta;
            }
        }

        /// <summary>
        /// 从微博属性里的CreatAt获取DateTime类型的时间
        /// </summary>
        /// <param name="dateString"></param>
        /// <returns></returns>
        public static DateTime GetTimeFromCreatAt(string dateString)
        {
            return DateTime.ParseExact(dateString, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// 获取单条微博页面Url
        /// </summary>
        /// <param name="weiboid"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string GetUrlFromId(string weiboid, string userid)
        {
            return string.Format("http://api.weibo.com/2/statuses/go?uid={0}&id={1}", userid, weiboid);
        }

        public static string UrlEncode(string str)
        {
            var sb = new StringBuilder();
            var byStr = Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            foreach (var t in byStr)
            {
                sb.Append(@"%" + Convert.ToString(t, 16));
            }
            return sb.ToString();
        }

        public static async Task<string> FileEncodeAsync(string path)
        {
            if (!File.Exists(path)) return null;
            return await Task.Run(() =>
            {
                var bytes = File.ReadAllBytes(path);
                return Encoding.GetEncoding("iso-8859-1").GetString(bytes);
            });
            
        }
    }
}
